package com.nacos.utils;

/**
 * @author: li chao
 * @Desc:
 * @create: 2024-07-03 10:46
 **/

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUrlConnectionExample {
    public static void main(String[] args) {
        try {
            // 创建URL对象
            URL url = new URL("http://www.example.com");

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为GET
            connection.setRequestMethod("GET");

            // 接收响应码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            // 如果响应码是HTTP_OK（200），则读取响应内容
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }

                in.close();

                // 打印结果
                System.out.println(response.toString());
            }

            // 关闭连接
            connection.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}